-- MassageRoom
-- Created by cheny3 Nov/08/2016
-- 按摩房

-- 初始化
function initMassageRoom(self)
    local function doCabin()
        DungeonActionM.go("do_building_bonus", self.gridData:getPos());
    end

    -- 判断消耗是否足够
    local function enoughToCost()
        -- 获取消耗
        local elementId = self.gridData.element;
        local args = DungeonM.queryElement(elementId).args;
        eventCost = args.cost;

        if type(eventCost[1]) == "number" then
            eventCost = { eventCost };
        end

        for _, cost in ipairs(eventCost) do
            if cost[1] == 1 then
                if ItemM.getAmount(ME.user, cost[2]) < cost[3] then
                    return string.format(getLocStr("something_not_enough"), ItemM.query(cost[2], "name"));
                end
            elseif cost[1] == 2 then
                if ME.user:queryAttrib(cost[2]) < cost[3] then
                    return string.format(getLocStr("something_not_enough"), FieldsM.getFieldName(cost[2]));
                end
            end
        end
        return true;
    end

    local function viewCabin()
        -- 探索点不足
        local ret = enoughToCost();
        if true ~= ret then
            alert(ret);
            return;
        end

        playCabinEffect(self.node);
        -- 小屋奖励
        performWithDelay(self, doCabin, 3.5);
    end

    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    if not buildingInfo then
        error("获取不到建筑查看配置，元素类型：" .. class);
        return;
    end

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            AudioM.playFx("ui_open1");
            self:updateBuildingVisit();

            if not DungeonM.isAllMonsterDead() then
                -- 需要击杀所有怪物方可拾取
                self:openBuildingView(nil, 0, buildingInfo["dialog2"], getLocStr("btn_text_leave"));
                return;
            end

            -- 打开建筑查看界面
            self:openBuildingView(viewCabin);
        end
    end

    -- 建筑图标
    local iconPath = getLevelItemIconPath(buildingInfo["icon"]);

    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
    self.iconPath = iconPath;

    -- 整体往上偏移一点
    self.item:setPositionY(20);

    if DungeonServiceM.queryDungeonAttrib("massage_room") >= 90 then
        -- 奖励拿满了
        self.icon:setVisible(false);
    end
end